<template>
    <div>
        <div class="crumbs">
            <el-breadcrumb separator="/">
                <el-breadcrumb-item>
                    <i class="el-icon-lx-cascades"></i> 用户管理
                </el-breadcrumb-item>
            </el-breadcrumb>
        </div>
        <div class="container">
            <div class="handle-box">
                <el-select v-model="query.role" placeholder="职务" class="handle-select mr10">
                    <el-option key="0" label="" value=""></el-option>
                    <el-option :key="item.id" :label="item.job" :value="item.id" v-for="item in roles"></el-option>
                </el-select>
                <el-input v-model="query.name" placeholder="输入姓名关键字进行搜索" class="handle-input mr10"></el-input>
                <el-button type="primary" icon="el-icon-search" @click="handleSearch">搜索</el-button>
            </div>
            <el-table
                    :data="tableData"
                    border
                    class="table"
                    ref="multipleTable"
                    header-cell-class-name="table-header"
            >
                <el-table-column prop="name" label="用户名"></el-table-column>
                <el-table-column prop="tel" label="手机号码"></el-table-column>
                <el-table-column label="照片(查看大图)" align="center">
                    <template slot-scope="scope">
                        <el-image
                                class="table-td-thumb"
                                :src="scope.row.thumb"
                                :preview-src-list="[scope.row.thumb]"
                        ></el-image>
                    </template>
                </el-table-column>
                <el-table-column prop="email" label="邮箱" width="200"></el-table-column>
                <el-table-column prop="job" label="职务"></el-table-column>
                <el-table-column prop="date" label="注册时间"></el-table-column>
                <el-table-column label="操作" width="180" align="center">
                    <template slot-scope="scope">
                        <el-button
                                type="text"
                                icon="el-icon-edit"
                                @click="handleEdit(scope.$index, scope.row)"
                        >编辑
                        </el-button>
                        <el-button
                                type="text"
                                icon="el-icon-delete"
                                class="red"
                                @click="handleDelete(scope.$index, scope.row)"
                        >删除
                        </el-button>
                    </template>
                </el-table-column>
            </el-table>
            <div class="pagination">
                <el-pagination
                        background
                        layout="total, prev, pager, next"
                        :current-page="query.pageIndex"
                        :page-size="query.pageSize"
                        :total="pageTotal"
                        @current-change="handlePageChange"
                ></el-pagination>
            </div>
        </div>

        <!-- 编辑弹出框 -->
        <el-dialog title="编辑" :visible.sync="editVisible" width="30%">
            <el-form ref="form" :model="form" label-width="70px">
                <div class="crop-demo">
                    <img :src="cropImg?cropImg:form.thumb" class="pre-img">
                    <div class="crop-demo-btn">选择图片
                        <input class="crop-input" type="file" name="image" accept="image/*" @change="setImage"/>
                    </div>
                </div>
                <br>
                <el-dialog title="裁剪图片" :visible.sync="dialogVisible" width="30%">
                    <vue-cropper ref='cropper' :src="imgSrc" :ready="cropImage" :zoom="cropImage"
                                 :cropmove="cropImage"
                                 style="width:100%;height:300px;"></vue-cropper>
                    <span slot="footer" class="dialog-footer">
                    <el-button @click="cancelCrop">取 消</el-button>
                    <el-button type="primary" @click="dialogVisible = false">确 定</el-button>
                </span>
                </el-dialog>
                <el-form-item label="姓名">
                    <el-input v-model="form.name"></el-input>
                </el-form-item>
                <el-form-item label="手机号码">
                    <el-input v-model="form.tel"></el-input>
                </el-form-item>
                <el-form-item label="邮箱">
                    <el-input v-model="form.email"></el-input>
                </el-form-item>
                <el-form-item label="角色">
                    <el-select v-model="form.rid" class="handle-select mr10">
                        <el-option key="0" label="" value=""></el-option>
                        <el-option :key="item.id" :label="item.job" :value="item.id" v-for="item in roles"></el-option>
                    </el-select>
                </el-form-item>
            </el-form>
            <span slot="footer" class="dialog-footer">
                <el-button @click="editVisible = false">取 消</el-button>
                <el-button type="primary" @click="saveEdit">确 定</el-button>
            </span>
        </el-dialog>
    </div>
</template>

<script>
    import service from "../../utils/request";
    import VueCropper from 'vue-cropperjs';

    export default {
        name: 'usermanage',
        data() {
            return {
                roles: [],
                imgSrc: '',
                dialogVisible: false,
                cropImg: '',
                query: {
                    role: '',
                    name: '',
                    pageIndex: 1,
                    pageSize: 10
                },
                tableData: [],
                editVisible: false,
                pageTotal: 0,
                form: {
                    date: "",
                    email: "",
                    id: 0,
                    job: "",
                    name: "",
                    password: "",
                    rid: 0,
                    tel: "",
                    thumb: "",
                    username: ""
                },
                idx: -1,
                id: -1
            };
        }, components: {
            VueCropper
        },
        created() {
            this.getData();
            this.getRole();
        },
        methods: {
            cancelCrop() {
                this.dialogVisible = false;
                this.cropImg = this.defaultSrc;
            },
            cropImage() {
                this.cropImg = this.$refs.cropper.getCroppedCanvas().toDataURL();
            },
            setImage(e) {
                const file = e.target.files[0];
                if (!file.type.includes('image/')) {
                    return;
                }
                const reader = new FileReader();
                reader.onload = (event) => {
                    this.dialogVisible = true;
                    this.imgSrc = event.target.result;
                    this.$refs.cropper && this.$refs.cropper.replace(event.target.result);
                };
                reader.readAsDataURL(file);
            },
            getData() {
                service.get("/users/getUsers", {
                    params: this.query
                }).then(res => {
                    this.tableData = res.message;
                    this.pageTotal = res.total;
                })
            },
            getRole() {
                service.get('/roles/getRoles').then(res => {
                    this.roles = res.message
                })
            },
            // 触发搜索按钮
            handleSearch() {
                this.$set(this.query, 'pageIndex', 1);
                this.getData();
            },
            // 删除操作
            handleDelete(index, row) {
                service.get('/users/check', {
                    params: {
                        userId: JSON.parse(localStorage.getItem("userInfo")).id
                    }
                }).then(res => {
                    if (res !== 2) {
                        this.$message.error('对不起，您没有权限')
                        return
                    }
                    // 二次确认删除
                    this.$confirm('确定要删除吗？', '提示', {
                        type: 'warning'
                    }).then(() => {
                        service.get('/users/delete/' + row.id).then(res => {
                            if (res.status == 1) {
                                this.$message.success('删除成功');
                                this.tableData.splice(index, 1);
                            } else {
                                this.$message.error('删除失败，请稍后再试');
                            }
                        })
                    }).catch(() => {
                    });
                })

            },
            // 编辑操作
            handleEdit(index, row) {
                this.imgSrc = ''
                this.cropImg = ''
                this.idx = index;
                for (let key in row) {
                    this.form[key] = row[key]
                }
                // this.form = row;
                this.editVisible = true;
            },
            // 保存编辑
            saveEdit() {
                let formData = new FormData();
                formData.append("base64", this.cropImg)
                for (let key in this.form) {
                    if (key !== 'date') {
                        formData.append(key, this.form[key])
                    }
                }
                service.post('/users/edit', formData).then(res => {
                    console.log(res)
                    this.editVisible = false;
                    this.$message.success(`修改第 ${this.idx + 1} 行成功`);
                    this.getData()
                })
                // this.$set(this.tableData, this.idx, this.form);
            },
            // 分页导航
            handlePageChange(val) {
                this.$set(this.query, 'pageIndex', val);
                this.getData();
            }
        }
    };
</script>

<style scoped>
    .handle-box {
        margin-bottom: 20px;
    }

    .handle-select {
        width: 120px;
    }

    .handle-input {
        width: 300px;
        display: inline-block;
    }

    .table {
        width: 100%;
        font-size: 14px;
    }

    .red {
        color: #ff0000;
    }

    .mr10 {
        margin-right: 10px;
    }

    .table-td-thumb {
        display: block;
        margin: auto;
        width: 40px;
        height: 40px;
    }

    .pre-img {
        width: 100px;
        height: 100px;
        background: #f8f8f8;
        border: 1px solid #eee;
        border-radius: 5px;
    }

    .crop-demo {
        display: flex;
        align-items: flex-end;
    }

    .crop-demo-btn {
        position: relative;
        width: 100px;
        height: 40px;
        line-height: 40px;
        padding: 0 20px;
        margin-left: 30px;
        background-color: #409eff;
        color: #fff;
        font-size: 14px;
        border-radius: 4px;
        box-sizing: border-box;
    }

    .crop-input {
        position: absolute;
        width: 100px;
        height: 40px;
        left: 0;
        top: 0;
        opacity: 0;
        cursor: pointer;
    }
</style>
